import React, { useEffect, useState } from "react";

const UploadImage = ({ onUpload, initImage }) => {
  const [preview, setPreview] = useState(null);
  const [file, setFile] = useState(null);

  // 处理文件选择
  const handleFileChange = (event) => {
    const selectedFile = event.target.files[0];
    if (selectedFile) {
      setFile(selectedFile);
      setPreview(URL.createObjectURL(selectedFile));
    }
  };

  useEffect(() => {
    if (initImage) {
      setPreview('http://'+window.location.hostname+':8089/'+initImage);
    }
  }, [initImage]);

  // 模拟上传
  const handleUpload = () => {
    if (file) {
      // 这里可以调用 API 上传文件
      onUpload(file);
    }
  };

  return (
    <div className="flex flex-col gap-4 ml-12">
      {/* 图片预览 */}
      {preview && (
        <img
          src={preview}
          alt="Preview"
          className="w-32 h-32 object-cover rounded-lg border"
        />
      )}

      {/* 文件输入框 */}
      <input
        type="file"
        accept="image/*"
        className="file-input file-input-bordered w-full max-w-xs"
        onChange={handleFileChange}
      />

      {/* 上传按钮 */}
      <button
        className="btn btn-primary max-w-xs"
        onClick={handleUpload}
        disabled={!file}
      >
        上传图片
      </button>
    </div>
  );
};

export default UploadImage;
